package com.zimi.core.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zimi.core.bean.AuthUser;
import com.zimi.mapper.SysUserMapper;
import com.zimi.model.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

@Slf4j
@Component
public class AuthUserService implements UserDetailsService {

    private final
    SysUserMapper sysUserMapper;


    @Autowired
    public AuthUserService(SysUserMapper sysUserMapper) {
        this.sysUserMapper = sysUserMapper;
    }

    @Override
    public AuthUser loadUserByUsername(String username) throws UsernameNotFoundException {
        AuthUser userInfo = new AuthUser();
        userInfo.setUsername(username);
        SysUser sysUser = new SysUser();
        sysUser.setLoginName(username);

        SysUser user = sysUserMapper.selectOne(new QueryWrapper<SysUser>().lambda().eq(SysUser::getUserState, 1).and(obj -> obj.eq(SysUser::getLoginName, sysUser.getLoginName()).or().eq(SysUser::getUserPhone, sysUser.getLoginName()).or().eq(SysUser::getUserEmail, sysUser.getLoginName())));
        if (user != null) {
            userInfo.setPassword(user.getUserLoginpwd());
        } else {
            throw new UsernameNotFoundException("密码或账号输入错误！");
        }
        Set<GrantedAuthority> authoritiesSet = new HashSet<GrantedAuthority>();
        GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_ADMIN"); // 模拟从数据库中获取用户角色

        authoritiesSet.add(authority);
        userInfo.setAuthorities(authoritiesSet);

        return userInfo;
    }

}
